package com.adlotto2.android.cronos.c2dm;

import java.net.URLDecoder;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;

import com.adlotto2.android.R;
import com.adlotto2.android.common.LottoAdFullActivity;
import com.adlotto2.android.util.ApplicationUtils;
import com.adlotto2.android.util.LottoAdConstants;

/**-
 * C2DM Receiver
 */
public class C2DMReceiver extends BroadcastReceiver {
	NotificationManager mNotiMgr;
	
	private String mMessage = "";
	private String mTitle = "";
	private String mAdSeq = "";
	
	private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {
    	mContext = context;
	    if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION"))
	    {
		    handleRegistration(context, intent);
		    Log.i("C2DMReceiver","Registration ID received!!");
	    }
	    else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE"))
	    {
	    	handleMessage(context, intent);
	    	Log.i("C2DMReceiver","Push Message received!!");
	    }
    }
    
    private void handleMessage(final Context context, Intent intent) 
    {
    	String msg = intent.getStringExtra("msg");
    	try {
    		msg = URLDecoder.decode(msg, "utf-8");
    	} catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	Log.e("BenTag", "Messsage : " + msg);
    	// JSON 파싱!!
    	if(parseJson(msg)) {
    		PushWakeLock.acquireCpuWakeLock(context);
    		new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					PushWakeLock.releaseCpuLock();
				}
    			
    		}, 2000);
    		
            Intent i = new Intent(context, ShowMsg.class);
            Bundle b = new Bundle();
            b.putString("title", mTitle);
            b.putString("msg", mMessage);
            b.putString("type", "0");
            b.putString("sendSeq", mAdSeq);
            
            i.putExtras(b);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        	
        	
        	
        	

        	NotificationManager notificationManager = (NotificationManager)context.getSystemService(Activity.NOTIFICATION_SERVICE);

        	// 해당 어플을 실행하는 이벤트를 하고싶을 때 아래 주석을 풀어주세요
        	// PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, 
        	// new Intent(context, 어플이 처음 시작되는 클래스명.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
        	Intent mainIntent = new Intent(context, LottoAdFullActivity.class);
    		mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP 
                    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    		mainIntent.putExtra("sendSeq", mAdSeq);
        	
        	PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
        	
        	/*Notification.Builder builder = new Notification.Builder(mContext);
        	builder.setContentTitle(mTitle);
        	builder.setContentText(mMessage);
        	builder.setSmallIcon(R.drawable.icon1_2);
        	builder.setContentIntent(pendingIntent);
        	builder.setVibrate(new long[] { 500, 100, 500, 100 });
        	builder.setAutoCancel(true);
        	Notification noti = builder.getNotification();*/
        	
        	
        	Notification notification =  new Notification(R.drawable.icon1_2, mTitle, System.currentTimeMillis());
                 
            // List에 표시될 항목
            notification.setLatestEventInfo(mContext, mTitle, mMessage, pendingIntent);
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
        	
        	notificationManager.notify(0, notification);
        	Vibrator vibe = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
        	vibe.vibrate(1500);

    	}
    	
        
    }
    
    private boolean parseJson(String str) {
    	if(str == null || str.equals("")) {
    		return false;
    	}
    	
    	JSONObject obj = null;
    	try {
    		obj = new JSONObject(str);
    		mTitle = obj.getString("title");
    		mMessage = obj.getString("message");
    		mAdSeq = obj.getString("adSeq");
    		
    		Log.i("BenTag", "parsed text \nTitle : " + mTitle + "\nMessage : " + mMessage + "\nAdSequence : " + mAdSeq);
    		
    		return true;
    		
    	} catch(JSONException e) {
    		e.printStackTrace();
    		return false;
    	}
    }
    
    private void handleRegistration(Context context, Intent intent) 
	{
    	String mRegistrationId = intent.getStringExtra("registration_id");
    	Log.d("BenTag","mRegistrationId : "+mRegistrationId);
		if (intent.getStringExtra("error") != null){
			
			String error = intent.getStringExtra("error");
			if (error == "SERVICE_NOT_AVAILABLE") 
			{
			} else if (error == "ACCOUNT_MISSING") 
			{
			} else if (error == "AUTHENTICATION_FAILED") 
			{
			} else if (error == "TOO_MANY_REGISTRATIONS") 
			{
			} else if (error == "INVALID_SENDER") 
			{
			} else if (error == "PHONE_REGISTRATION_ERROR") 
			{
			}
		} 
		else if (intent.getStringExtra("unregistered") != null){
		}else if (mRegistrationId != null){
						
			ApplicationUtils.setStrPreferences(context, LottoAdConstants.PREFER_REGISTRATION_ID, mRegistrationId);
			
		}
	}
}